<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class GoodsController extends Controller
{
	//显示有哪些分类
    public function getAdd(){
        $types=DB::table('type')->select(DB::raw('*, concat(path,",",id) as pd'))->orderBy('pd')->get();
    	// dd($types);
        return view('admin.goods.add',['types'=>$types]);
    }
    //开始插入商品
    public function postInsert(Request $request){
    	 //表单验证
        $this->validate($request,[
            'title'=>'required',
            'price'=>'required',
            'store'=>'required|regex:/^\d+$/',
            'detail'=>'required',
            'status'=>'required',
            ],[
            'title.required'=>'标题不能为空',
            'price.required'=>'价格不能为空',
            'store.required'=>'库存不能为空',
            'store.regex'=>'库存只能为数字',
            'detail.required'=>'详情不能为空',
            'status.required'=>'状态不能为空',
            ]);
        //获取提交值
        $data=$request->except(['_token','goods_img']);
        //拼接字符串(color,size)
        $data['color']=implode('@@@',$data['color']);
        $data['size']=implode('@@@',$data['size']);
        $data['time']=time();

        $id=DB::table('goods')->insertGetId($data);

        //文件处理
        $result=[];
        if($request->hasFile('goods_img')){
            $files=$request->file('goods_img');
            foreach($files as $k=>$v){
                $tmp=[];
                //后缀名
                $suffix = $v->getClientOriginalExtension();
                //拼接文件名
                $fileName= time().rand(100000,999999).'.'.$suffix;
                //目录名称
                $dir='./uploads/'.date('Ymd');
                //一定文件
                $v->move($dir,$fileName);
                //将绝对路径写入数据库
                $tmp['path']=trim($dir.'/'.$fileName,'.');
                $tmp['gid']=$id;
                $result=$tmp;
            }
        $res=DB::table('goods_img')->insert($result);
        }
        //数据写入数据库
        
        if($res&&$id){
            return redirect('goods/list')->with('info','添加成功');
        }else{
            return back()->with('error','添加失败');
        }
    }

    /**
    *
    *列表页显示
    **/
    public function getList(Request $request)
    {
        $goods=DB::table('goods')
            ->orderBy('time','desc')
            ->where(function($query)use($request){
                $keyword=$request->input('keyword');
                if($keyword){
                    $query->where('title','like','%'.$keyword.'%');
                }
            })
            ->paginate($request->input('num',10));
        foreach($goods as $k=>$value){
            $p = DB::table('type')->where('id','=',$value->type_id)->first();
            if($p){
                $path='';
                $arr=explode(",",$p->path);
                foreach($arr as $v){
                    // global $value;
                    $j=DB::table('type')->select('name')->where('id','=',$v)->first();
                    if($j){
                        $path .= $j->name.'/';
                    }else{
                        $path .= '顶级分类/';
                    }
                }
                $path .= $p->name;
            }else{
                $path = '顶级分类/';
            }
            $value->path=$path;
            if($value->status == 1){
                $value->status ='正常';
            }else{
                $value->status ='冻结';
            }
        }
        return view('admin.goods.list',['goods'=>$goods,'request'=>$request]);
    }

    /**
    *商品修改显示
    */
    public function getEdit(Request $request){
        $id=$request->input('id');

        $goods=DB::table('goods')->where('id',$id)->first();
        if($goods->type_id=='0'){
            $path='顶级分类';
        }else{
            $path=DB::table('type')->where('id','=',$goods->type_id)->value('name');
        }
        $size=explode('@@@',$goods->size);
        $color=explode('@@@',$goods->color);
        $img=DB::table('goods_img')->where('gid','=',$goods->id)->get();
        return view('admin.goods.edit',['goods'=>$goods,'size'=>$size,'color'=>$color,'path'=>$path,'img'=>$img]);
    }
    //修改
    public function postUpdate(Request $request){
        $id=$request->id;
        //获取更新的文章内容
        $newc=$request->detail;
        //匹配要更新文章内图片
        $z1='/src="(.*?)"/';
        preg_match_all($z1, $newc, $newimg);
        if(isset($newimg[1])){
            //获取旧文章的图片
            $img=DB::table('goods')->where('id',$id)->value('detail');
            $z='/src="(.*?)"/';
            preg_match_all($z, $img, $nimg);
            if(isset($nimg[1])){
                foreach ($nimg[1] as $k => $v) {
                    if(!in_array($v, $newimg[1])){
                        @unlink('.'.$v);
                    }
                }
            }
        }
        //去除
        $data=$request->except(['_token','id']);
        $data['size']=implode('@@@',$data['size']);
        $data['color']=implode('@@@',$data['color']);
       
        $res=DB::table('goods')->where('id','=',$request->input('id'))->update($data);
        if($res){
            return redirect('goods/list')->with('info','修改成功');
        }else{
            return back()->with('error','修改失败');
        }
    }
    
    //删除
    public function getDrop(Request $request){
        //获取id
        $id=$request->input('id');
        //查询文章内所有的图片路径
        $str=DB::table('goods')->where('id','=',$id)->get();
        //正则匹配detail内图片路径
        $z='/src="(.*?)"/';
        preg_match_all($z, $str[0]->detail, $c);
        //遍历删除文章内图片
        foreach($c[1] as $k=>$v){
            $img_path='.'.$v;
            @unlink($img_path);
        }
        $str2=DB::table('goods_img')->where('gid','=',$id)->get();
        if($str2){
            @unlink('.'.$str2[0]->path);
        }
        //删除goods表
        $data=DB::table('goods')->where('id','=',$id)->delete();
        //删除goods_img表
        $data2=DB::table('goods_img')->where('gid','=',$id)->delete();
        if($data && $data2){
            return redirect('goods/list')->with('info','删除成功');
        }else{
            return back()->with('error','删除失败');
        }
    }

}
